package me.liuhui.mall.manager.service.security;

import cn.hutool.core.util.StrUtil;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class KaptchaAuthenticationProvider extends DaoAuthenticationProvider {

    public static final String CAPTCHA_NAME = "captcha";

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String kaptcha = req.getParameter(CAPTCHA_NAME);
        String sessionKaptcha = (String) req.getSession().getAttribute(CAPTCHA_NAME);
        if (kaptcha != null && StrUtil.equalsIgnoreCase(kaptcha, sessionKaptcha)) {
            return super.authenticate(authentication);
        }
        throw new CaptchaException("验证码输入错误");
    }
}
